-module(audio_manager).
-export([upload/3, get_audios/2, rate/2]).
-include("records.hrl").
-define(DIR, "/home/nadia/Escriptori/Nadia/Tullitito/Programming/LYME/spanskandsueco/www/audio/").


% Store the rating of a audio file of Teacher in the DB
rate(Teacher, Rating) ->
	{atomic, [{user, _, _, _, _, _, _, _, _, _, _, _, _, Times, CurrentRating, _}]} = db_user:get_user(Teacher),
	{ok, [RatingInt], _} = io_lib:fread("~d", Rating),
	NewRating = (Times / (Times + 1)) * CurrentRating + (1 / (Times + 1)) * RatingInt,
	db_user:add_times_listened(Teacher, NewRating),
	ok.	



% Get a list of audios between Offset and Offset+5
get_audios(Language, Offset) ->
	{atomic, R} = db_audio:get_by_language(Language),
	Total = length(R),
	
	if Total =:= 0 ->
		{array, [Total | []]};
	true ->
		% Obtain the list of audios
		LAudios = db_audio:get_with_offset(Offset, Total, Language),
	
		% Obtain from the list of homeworks the information that interests us
		Data = [ {struct, [
			{user, atom_to_list(User)},
			{filename, FileName},
			{text, Text}]}
			|| {audio, _, User, FileName, Text, _} <- LAudios],
			
		{array, [Total | Data]}
	end.

% Upload the file into the server and store in the database a new file entry
upload(A, State, Cookie) ->
	{result, [_,{body, Text}|Res]} = yaws_api:parse_multipart_post(A),
	case addFileChunk(A, Res, State#upload{last=true}) of
		{ok, FileName} ->
			{ok, Session} = yaws_api:cookieval_to_opaque(Cookie),
			Language = case Session#session.speak_swedish of
				1 ->
					swedish;
				0 ->
					spanish
			end,
			db_audio:insert(Session#session.user, Text, FileName, Language),
			db_user:add_uploaded_audios(Session#session.user),
			NewSession = Session#session{
						uploaded_audios = Session#session.uploaded_audios + 1},
			yaws_api:replace_cookie_session(Cookie, NewSession),
			ok;
		error ->
			error
	end.



addFileChunk(A, [{part_body, Data}|Res], State) ->
	addFileChunk(A, [{body, Data}|Res], State);

addFileChunk(_A, [], State) when
	State#upload.last==true,
	State#upload.filename /= undefined,
	State#upload.fd /= undefined ->
		file:close(State#upload.fd),
		ok;

addFileChunk(_A, [], State) when State#upload.last==true ->
	error;

addFileChunk(A, [{head, {_Name, Opts}}|Res], State ) ->
	case lists:keysearch(filename, 1, Opts) of
		{value, {_, Fname0}} ->
			Fname = yaws_api:sanitize_file_name(basename(Fname0)),
			file:make_dir(?DIR),
			case file:open([?DIR, Fname] ,[write]) of
				{ok, Fd} ->
					S2 = State#upload{filename = Fname, fd = Fd},
					addFileChunk(A, Res, S2),
					{ok, Fname};
				_Err ->
					error
			end;
		false ->
			error
	end;

addFileChunk(A, [{body, Data}|Res], State) when State#upload.filename /= undefined ->
	case file:write(State#upload.fd, Data) of
		ok ->
			addFileChunk(A, Res, State);
		_Err ->
			error
	end.


basename(FilePath) ->
	case string:rchr(FilePath, $\\) of
		0 ->
			filename:basename(FilePath);
		N ->
			basename(string:substr(FilePath, N+1))
	end.
